﻿function MindMap() {
    this.Id = null;
    this.Nodes = new Array();

    var current = this;

    this.Connections = null;

    this.Show = function () {
        $.each(this.Nodes, function (index, node) {
            node.Show();
        });
        this.BuildConnections();
    };

    this.BuildConnections = function () {
        this.Connections = new Array();

        $.each(this.Nodes, function (index, node) {
            if (node.Parent != null) {
                current.Connections.push(raphael.connection(node.Parent.GraphicsElement, node.GraphicsElement, "#fff"));
            }
        });
    };

    this.Insert = function (parentNode) {
        var node = new MindMapNode();
        node.Id = Core.GetNewGuid();
        node.Text = "New" + this.Nodes.length;
        node.Position = { x: parentNode.Position.x + 100, y: parentNode.Position.y + 100, width: 100, height: 50 };
        node.MindMap = this;
        node.Parent = parentNode;

        this.Nodes.push(node);

        node.Show();

        this.Connections.push(raphael.connection(parentNode.GraphicsElement, node.GraphicsElement, "#fff"));
    };

    this.Delete = function (node) {
        for (var i = 0; i < this.Nodes.length; ) {
            if (this.Nodes[i].Parent == node)
                current.Delete(this.Nodes[i]);
            else
                i++;
        };

        this.Nodes.splice(this.Nodes.indexOf(node), 1);

        var connection = this.GetConnection(node.Parent, node);
        if (connection != null) {
            this.Connections.splice(this.Connections.indexOf(connection), 1);
            connection.line.remove();
        }

        node.Dispose();
    };

    this.GetConnection = function (from, to) {
        var connection = null;

        $.each(this.Connections, function (index, item) {
            if (item.from == from.GraphicsElement && item.to == to.GraphicsElement) {
                connection = item;
                return false;
            }
        });

        return connection;
    }
}